package com.yunhe.marketing.controller;

import com.alibaba.excel.EasyExcel;
import com.yunhe.common.annotation.OperationRecord;
import com.yunhe.common.constant.SystemConsts;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.UniqueConstraintsException;
import com.yunhe.common.model.ResultObject;
import com.yunhe.common.model.mybatis.PageResult;
import com.yunhe.common.util.StringUtil;
import com.yunhe.marketing.domain.Enterprise;
import com.yunhe.marketing.domain.FilterCondition;
import com.yunhe.marketing.listener.AQCUploadDataListener;
import com.yunhe.marketing.listener.UploadDataListener;
import com.yunhe.marketing.model.ClueFilterCondition;
import com.yunhe.marketing.model.EnterpriseUpload;
import com.yunhe.marketing.model.EnterpriseUploadAQC;
import com.yunhe.marketing.service.IClueRepositoryService;
import com.yunhe.marketing.service.IDemandRepositoryService;
import com.yunhe.marketing.util.ExcelUtils;
import com.yunhe.marketing.util.MyHeaderUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import com.yunhe.common.util.CollectionUtil;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: ClueController
 * @Description:
 * @author: GongDaCheng
 * @Date: 10:18 2021/2/24
 */
@Api(value = "clue", description = "线索库维护", tags = {"Model_Clue"})
@RestController
@RequestMapping("/clueRepository")
public class ClueController {
    @Autowired
    IClueRepositoryService clueRepositoryService;
    @Autowired
    IDemandRepositoryService demandRepositoryService;

    @Autowired
    private MyHeaderUtil headerUtil;


    private  final Logger logger = LoggerFactory.getLogger(ClueController.class);

    @ApiOperation("根据条件筛选线索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页展示的条数", dataType = "int", paramType = "query")
    })
    @GetMapping(value = "/clueByCondition")
    public ResponseEntity<ResultObject> selectClueByClueQueryCondition(@ModelAttribute ClueFilterCondition clueFilterCondition,
                                                                       @RequestParam("page") int page,
                                                                       @RequestParam("size") int size) throws ParseException {
        PageResult result = clueRepositoryService.selectClueByClueQueryCondition(clueFilterCondition,page ,size );
        return new ResponseEntity<>(new ResultObject<>(result), HttpStatus.OK);
    }

    @ApiOperation("保存筛选条件")
    @ApiImplicitParams({
//            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "conditionName", value = "筛选条件名字", dataType = "String", paramType = "query")
    })
    @PostMapping(value = "/condition")
    @OperationRecord(menu = "线索需求库管理", actionType = SystemConsts.ACTION.ADD)
    public ResponseEntity<ResultObject> saveClueFilterCondition(@RequestParam("conditionName") String conditionName,
                                                                @RequestBody ClueFilterCondition clueFilterCondition) throws UniqueConstraintsException, ArgumentErrorException {
        Long userId = headerUtil.getHeaderUser();
        if(userId == null){
            throw new ArgumentErrorException("未获取到登录信息，请重新登录！");
        }
        FilterCondition filterCondition = clueRepositoryService.saveClueFilterCondition(userId, conditionName, clueFilterCondition);
        return new ResponseEntity<>(new ResultObject<>(filterCondition), HttpStatus.OK);
    }

    @ApiOperation("查看已保存的条件组")
    @ApiImplicitParams({
//            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页的条数", dataType = "int", paramType = "query")
    })
    @GetMapping(value = "/savedCondition")
    public ResponseEntity<ResultObject> viewSavedFilterCondition(@RequestParam("page") int page,
                                                                 @RequestParam("size") int size) throws ArgumentErrorException {
        Long userId = headerUtil.getHeaderUser();
        if(userId == null){
            throw new ArgumentErrorException("未获取到登录信息，请重新登录！");
        }
        PageResult result = clueRepositoryService.viewSavedFilterCondition(userId ,page, size);
        return new ResponseEntity<>(new ResultObject<>(result), HttpStatus.OK);
    }

    @ApiOperation("根据关键字搜索条件组")
    @ApiImplicitParams({
//            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "keyName", value = "关键字", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页的条数", dataType = "int", paramType = "query")
    })
    @GetMapping(value = "/savedConditionByKeyName")
    public ResponseEntity<ResultObject> selectFilterConditionByKeyName(@RequestParam("keyName") String keyName,
                                                                       @RequestParam("page") int page,
                                                                       @RequestParam("size") int size) throws ArgumentErrorException {
        Long userId = headerUtil.getHeaderUser();
        if(userId == null){
            throw new ArgumentErrorException("未获取到登录信息，请重新登录！");
        }
        PageResult result = clueRepositoryService.selectFilterConditionByKeyName(userId, keyName, page, size);
        return new ResponseEntity<>(new ResultObject<>(result), HttpStatus.OK);
    }


    @ApiOperation("根据条件组ID删除条件组")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "条件组id", dataType = "long", paramType = "query"),
    })
    @DeleteMapping(value = "/savedConditionById")
    @OperationRecord(menu = "线索需求库管理", actionType = SystemConsts.ACTION.DELETE)
    public ResponseEntity<ResultObject> deleteById(@RequestParam("id") Long id){
        int result = clueRepositoryService.deleteById(id);
        return new ResponseEntity<>(new ResultObject<>(result), HttpStatus.OK);
    }

    @ApiOperation("根据条件组ID查询条件组")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "条件组id", dataType = "long", paramType = "query"),
    })
    @GetMapping(value = "/savedConditionById")
    public ResponseEntity<ResultObject> selectById(@RequestParam("id")Long id){
        FilterCondition result = clueRepositoryService.selectFilterConditionByConditionId(id);
        return new ResponseEntity<>(new ResultObject<>(result), HttpStatus.OK);
    }

    @ApiOperation("根据企业id查询线索（查看线索详情）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "企业id", dataType = "long", paramType = "query")
    })
    @GetMapping(value = "/enterpriseDetail")
    public ResponseEntity<ResultObject> selectClueById(@Param("id") Long id){
        Enterprise result = clueRepositoryService.selectClueById(id);
        return new ResponseEntity<>(new ResultObject<>(result), HttpStatus.OK);
    }

    @ApiOperation("分配任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "任务id，多个任务用“，”分隔", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "responsiblePersonId", value = "负责人Id", required = true, dataType = "Long", paramType = "query")
    })
    @PostMapping("/assign")
    @OperationRecord(menu = "线索需求库管理", actionType = SystemConsts.ACTION.EDIT)
    public ResponseEntity<ResultObject> assign(@RequestParam String ids,
                                               @RequestParam Long responsiblePersonId) throws ArgumentErrorException {
        List<Enterprise> enterpriseList = clueRepositoryService.assign(ids, responsiblePersonId);
        return new ResponseEntity<>(new ResultObject<>(enterpriseList), HttpStatus.OK);
    }

    @ApiOperation("数据导入")
    @PostMapping("/upload")
    @OperationRecord(menu = "线索需求库管理", actionType = SystemConsts.ACTION.ADD)
    public ResponseEntity<ResultObject> upload(@RequestBody MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), EnterpriseUpload.class, new UploadDataListener(demandRepositoryService)).sheet().doRead();
        return new ResponseEntity<>(new ResultObject<>("success"), HttpStatus.OK);
    }

    @ApiOperation("爱企查数据导入")
    @PostMapping("/uploadAQC")
    //@OperationRecord(menu = "线索需求库管理", actionType = SystemConsts.ACTION.ADD)
    public ResponseEntity<ResultObject> uploadAQC(@RequestBody MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        EasyExcel.read(file.getInputStream(), EnterpriseUploadAQC.class, new AQCUploadDataListener(demandRepositoryService , filename)).sheet().doRead();
        return new ResponseEntity<>(new ResultObject<>("success"), HttpStatus.OK);
    }

    @ApiOperation("数据导出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "线索的id", required = true, dataType = "String", paramType = "query"),
    })
    @GetMapping("/export")
    @OperationRecord(menu = "线索需求库管理", actionType = SystemConsts.ACTION.EXPORT)
    public ResponseEntity<ResultObject> upload(@RequestParam String ids,
                                               HttpServletResponse httpServletResponse) throws ArgumentErrorException {
        Long exportPeopleId = headerUtil.getHeaderUser();
        if(exportPeopleId == null){
            throw new ArgumentErrorException("未获取到登录信息，请重新登录！");
        }
        List<Enterprise> list = demandRepositoryService.export(ids , exportPeopleId, httpServletResponse);
        List<EnterpriseUpload> data = new ArrayList<>();
        for (Enterprise enterprise : list){
            data.add(convertToEnterpriseUpload(enterprise));
        }
        if (!CollectionUtil.isEmpty(data)){
            ExcelUtils.export(data,httpServletResponse,EnterpriseUpload.class);
        }
        return null;
    }
    private EnterpriseUpload convertToEnterpriseUpload(Enterprise enterprise){
        String addString = "万";
        EnterpriseUpload enterpriseUpload = new EnterpriseUpload();
        BeanUtils.copyProperties(enterprise,enterpriseUpload);
        if (!StringUtil.isEmpty(enterpriseUpload.getRegisteredCapital())){
            enterpriseUpload.setRegisteredCapital(enterprise.getRegisteredCapital()+addString);
        }
        if (!StringUtil.isEmpty(enterpriseUpload.getPaidInCapital())){
            enterpriseUpload.setPaidInCapital(enterprise.getPaidInCapital()+addString);
        }
        if (!StringUtil.isEmpty(enterpriseUpload.getAnnualTurnover())){
            enterpriseUpload.setAnnualTurnover(enterprise.getAnnualTurnover()+addString);
        }
        if (!StringUtil.isEmpty(enterprise.getContactNumber())) {
            if (enterprise.getContactNumber().contains(",")) {
                enterpriseUpload.setContactNumber(enterprise.getContactNumber().split(",")[0]);
                enterpriseUpload.setOtherNumber(enterprise.getContactNumber().replaceFirst(enterprise.getContactNumber().split(",")[0].concat(","), ""));
            }
        }
        if(!StringUtil.isEmpty(enterprise.getEmail())) {
            if (enterprise.getEmail().contains(",")) {
                enterpriseUpload.setEmail(enterprise.getEmail().split(",")[0]);
                enterpriseUpload.setOtherEmail(enterprise.getEmail().replaceFirst(enterprise.getEmail().split(",")[0], ""));
            }
        }
        return enterpriseUpload;
    }
}